﻿using BCCommon;
using BCEntity.Sim.Company.CompanyBusinessType;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.Sim.Company.CompanyBusinessType
{
    /// <summary>
    /// 公司业务类型
    /// </summary>
	public class CompanyBusinessTypeData : ICompanyBusinessTypeData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM CompanyBusinessType";
        private const string QUERY = @"SELECT CompanyBusinessTypeId,BusinessTypeName,BusinessTypeCode,CreateTime FROM CompanyBusinessType";
        public CompanyBusinessTypeData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }

        public async Task<bool> Exists(int companyBusinessTypeId)
        {
            string sql = string.Format(@"{0} WHERE CompanyBusinessTypeId=?CompanyBusinessTypeId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyBusinessTypeId", companyBusinessTypeId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string companyBusinessTypeCode)
        {
            string sql = string.Format(@"{0} WHERE BusinessTypeCode=?BusinessTypeCode", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessTypeCode", companyBusinessTypeCode?.Trim(), DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<CompanyBusinessTypeEntity> Add(CompanyBusinessTypeEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("CompanyBusinessType", new string[] { "BusinessTypeName", "BusinessTypeCode" });
            sql = string.Format("{0} {1} WHERE CompanyBusinessTypeId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessTypeName", entity.BusinessTypeName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?BusinessTypeCode", entity.BusinessTypeCode?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<CompanyBusinessTypeEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<CompanyBusinessTypeEntity> Update(CompanyBusinessTypeEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("CompanyBusinessType", new string[] { "BusinessTypeName", "BusinessTypeCode" }, new string[] { "CompanyBusinessTypeId" });
            sql = string.Format("{0} {1} WHERE CompanyBusinessTypeId=?CompanyBusinessTypeId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyBusinessTypeId", entity.CompanyBusinessTypeId, DbType.Int32, size: 11);
            parameters.Add("?BusinessTypeName", entity.BusinessTypeName?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?BusinessTypeCode", entity.BusinessTypeCode?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<CompanyBusinessTypeEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(int companyBusinessTypeId)
        {
            string sql = @"DELETE FROM CompanyBusinessType WHERE CompanyBusinessTypeId=?CompanyBusinessTypeId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyBusinessTypeId", companyBusinessTypeId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<CompanyBusinessTypeEntity> GetEntity(int companyBusinessTypeId)
        {
            string sql = string.Format(@"{0} WHERE CompanyBusinessTypeId=?CompanyBusinessTypeId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?CompanyBusinessTypeId", companyBusinessTypeId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<CompanyBusinessTypeEntity>(sql, parameters);
        }

        public async Task<CompanyBusinessTypeEntity> GetEntity(string companyBusinessTypeCode)
        {
            string sql = string.Format(@"{0} WHERE BusinessTypeCode=?BusinessTypeCode", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessTypeCode", companyBusinessTypeCode, DbType.AnsiString);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<CompanyBusinessTypeEntity>(sql, parameters);
        }

        public async Task<IEnumerable<CompanyBusinessTypeEntity>> GetList()
        {
            return await this.databaseContext.Slave.QueryAsync<CompanyBusinessTypeEntity>(QUERY);
        }

        public async Task<(IEnumerable<CompanyBusinessTypeEntity>, int)> Query(string companyBusinessTypeName, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(companyBusinessTypeName))
            {
                wheres.Add("BusinessTypeName LIKE CONCAT('%',CONCAT(?BusinessTypeName,'%'))");
                parameters.Add("?BusinessTypeName", companyBusinessTypeName?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM CompanyBusinessType {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryMultipleAsync<CompanyBusinessTypeEntity, int>(sql, parameters);
        }
    }
}
